package com.yxq.mdt.app.application;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.model.ShareBean;

import java.io.File;
import java.util.List;
import java.util.Map;


/**
 * @描述 Umeng Share 工具类
 * @作者 yd
 * @创建日期 2019/9/4 0004 10:21
 */
public class UmengShareHelper {

    /**
     * 判断微信是否可用
     *
     * @param context 上下文
     * @return
     */
    public static boolean isWeChatAvailable(@NonNull Context context) {

        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.WECHAT_ID);
        if (api.isWXAppInstalled()) {
            return true;
        } else {

            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.tencent.mm")) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 检测是否安装支付宝
     *
     * @param context 上下文
     * @return
     */
    public static boolean isAlipayAvailable(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    /**
     * 登录获取用户信息
     *
     * @param callback 授权回调
     */
    public static void loginWX(Activity activity, final ShareSDKCallback<Map<String, String>> callback) {

        UMShareAPI.get(activity).getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (BuildConfig.DEBUG) {
                    for (String key : map.keySet()) {
                        Log.e("PlatformActionListener", key + "," + map.get(key));
                    }
                }
                if ("男".equals(map.get("gender"))) {
                    map.put("gender", "1");
                } else if ("女".equals(map.get("gender"))) {
                    map.put("gender", "2");
                } else {
                    map.put("gender", "0");
                }
                callback.onComplete(SHARE_MEDIA.WEIXIN.name(), map);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                if ("错误码：2008 错误信息：没有安装应用".equals(throwable.getMessage())) {
                    callback.onError("请先安装微信");
                    return;
                }
                callback.onError(throwable != null ? throwable.getMessage() : "微信授权异常");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    /**
     * 登录获取用户信息
     *
     * @param callback 授权回调
     */
    public static void loginQQ(Activity activity, final ShareSDKCallback<Map<String, String>> callback) {

        UMShareAPI.get(activity).getPlatformInfo(activity, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (BuildConfig.DEBUG) {
                    for (String key : map.keySet()) {
                        Log.e("PlatformActionListener", key + "," + map.get(key));
                    }
                }
                if ("男".equals(map.get("gender"))) {
                    map.put("gender", "1");
                } else if ("女".equals(map.get("gender"))) {
                    map.put("gender", "2");
                } else {
                    map.put("gender", "0");
                }
                callback.onComplete(SHARE_MEDIA.WEIXIN.name(), map);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                if ("错误码：2008 错误信息：没有安装应用".equals(throwable.getMessage())) {
                    callback.onError("请先安装QQ");
                    return;
                }
                callback.onError("" + throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    /**
     * 微信分享
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param shareBean       分享数据
     */
    public static void shareWeChat(Activity context, UMShareListener umShareListener, ShareBean shareBean) {
        if (!isWeChatAvailable(context)) {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
            return;
        }

        if (!TextUtils.isEmpty(shareBean.getImageUrl())) {
            shareWeb(context, shareBean.getUrl(), shareBean.getTitle(), shareBean.getText(), shareBean.getImageUrl(), -1, SHARE_MEDIA.WEIXIN, umShareListener);
        } else {
            shareWeb(context, shareBean.getUrl(), shareBean.getTitle(), shareBean.getText(), null, R.mipmap.ic_launcher, SHARE_MEDIA.WEIXIN, umShareListener);
        }

    }

    /**
     * 微信朋友圈分享
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param shareBean       分享数据
     */
    public static void shareWeChatMoments(Activity context, UMShareListener umShareListener, ShareBean shareBean) {
        if (!isWeChatAvailable(context)) {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
            return;
        }

        if (!TextUtils.isEmpty(shareBean.getImageUrl())) {
            shareWeb(context, shareBean.getUrl(), shareBean.getTitle(), shareBean.getText(), shareBean.getImageUrl(), -1, SHARE_MEDIA.WEIXIN_CIRCLE, umShareListener);
        } else {
            shareWeb(context, shareBean.getUrl(), shareBean.getTitle(), shareBean.getText(), null, R.mipmap.ic_launcher, SHARE_MEDIA.WEIXIN_CIRCLE, umShareListener);
        }

    }

    /**
     * 微信分享图片
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param shareBean       分享数据
     */
    public static void shareWeChatImg(Activity context, UMShareListener umShareListener, ShareBean shareBean) {
        if (isWeChatAvailable(context)) {
            UMImage image = new UMImage(context, shareBean.getImageUrl());//网络图片
            UMImage thumb = new UMImage(context, shareBean.getImageUrl());
            image.setThumb(thumb);
            new ShareAction(context).setPlatform(SHARE_MEDIA.WEIXIN).withText("贝壳绘本").withMedia(image).setCallback(umShareListener).share();
        } else {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 微信分享图片
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param img             分享数据
     */
    public static void shareWeChatImg(Activity context, UMShareListener umShareListener, String img) {
        if (isWeChatAvailable(context)) {
            UMImage image = new UMImage(context, new File(img));
            new ShareAction(context).setPlatform(SHARE_MEDIA.WEIXIN).withText("贝壳绘本").withMedia(image).setCallback(umShareListener).share();
        } else {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 微信朋友圈分享图片
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param shareBean       分享数据
     */
    public static void shareWeChatMomentsImg(Activity context, UMShareListener umShareListener, ShareBean shareBean) {
        if (!isWeChatAvailable(context)) {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
            return;
        }
        UMImage image = new UMImage(context, shareBean.getImageUrl());
        UMImage thumb = new UMImage(context, shareBean.getImageUrl());
        image.setThumb(thumb);
        new ShareAction(context).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).withText("贝壳绘本").withMedia(image).setCallback(umShareListener).share();
    }

    /**
     * 微信朋友圈分享图片
     *
     * @param context         上下文
     * @param umShareListener 回调
     * @param img             分享数据
     */
    public static void shareWeChatMomentsImg(Activity context, UMShareListener umShareListener, String img) {
        if (!isWeChatAvailable(context)) {
            Toast.makeText(context, "请安装微信后再来分享哟～", Toast.LENGTH_LONG).show();
            return;
        }
        UMImage image = new UMImage(context, new File(img));
        new ShareAction(context).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).withText("贝壳绘本").withMedia(image).setCallback(umShareListener).share();
    }

    /**
     * 分享链接
     */
    private static void shareWeb(final Activity activity, String WebUrl, String title, String description, String imageUrl,
                                 int imageID, SHARE_MEDIA platform, UMShareListener umShareListener) {
        UMWeb web = new UMWeb(WebUrl);      //链接地址
        web.setTitle(title);                                      //标题
        web.setDescription(description);               //描述
        if (TextUtils.isEmpty(imageUrl)) {
            web.setThumb(new UMImage(activity, imageID));   //本地缩略图
        } else {
            web.setThumb(new UMImage(activity, imageUrl));  //网络缩略图
        }
        new ShareAction(activity)
                .setPlatform(platform)
                .withMedia(web)
                .setCallback(umShareListener)
                .share();

    }

    /**
     * 请求回调
     */
    public interface ShareSDKCallback<T> {
        void onComplete(String name, T t);

        void onError(String errMsg);
    }
}
